<template>
    <div class="mainContent">
        <path-tracking :path='path' />
        <div class="pageContent qxz_tabList">
            <div class="createBtn" v-if="createBtns">
                <div @click="createBtn"><img src="@/assets/img/button_plus.png" class="iconPlus" />创建客户</div>
            </div>
            <el-tabs v-model="activeName" class="customerTabNavs tabNavsBig">
                <el-tab-pane 
                    v-for="(item, index) in tabNavs"
                    :key="index" 
                    :label="item.label"
                    :name="item.name"
                >
                    <div class="table-title">
                        <div class="table-icon"></div>
                        <div class="table-fl">查询条件</div>
                    </div>
                    <advanced-search
                        style="margin-top: -10px;"
                        v-show="activeName === item.name"
                        :ref="item.name" 
                        :option="item.options"
                        @onSearch="goSearch(item.name, index)"
                    />
                    <div class="tableLayout">
                        <el-row>
                            <div class="common-table-title">
                                <div class="common-table-icon"></div>
                                <div class="common-table-fl">客户列表</div>
                                <div class="common-btn-group" v-if="activeName === 'allSearchBox'">
                                    <div class="operate-btn" v-if="exportIcon">
                                        <img src="@/assets/img/icon_upload.png" class="exportIcon" />
                                        导出
                                    </div>
                                </div>
                            </div>
                        </el-row>
                        <el-row style="padding: 0 16px;background:#fff;border-radius: 0 0 8px 8px;">
                            <el-table
                                :data="item.tableContent"
                                max-height="550"
                                ref="recordList"
                            >
                                <el-table-column
                                    v-for='(ele, ind) in item.tableConfig'
                                    :key="ind"
                                    :prop='ele.prop'
                                    :label='ele.label'
                                    :fixed="ele.fixed"
                                    :width="ele.width"
                                    align='center'
                                >
                                    <template slot-scope="scope">
                                        <div>
                                            {{translateData(scope.row, ele)}}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    fixed="right"
                                    label="操作"
                                    width="300"
                                    align='center'
                                >
                                    <template slot-scope="scope">
                                        <div class="btnsCan">
                                            <div v-if="seeDetail" @click="goDetail(scope.row)" class="operateBtn">
                                                查看
                                            </div>
                                            <div v-if="editBtn" @click="goEdit(scope.row)" class="operateBtn">
                                                编辑
                                            </div>
                                            <div @click="goReturnVisit(scope.row)" v-if="scope.row.customerType != 3 && returnVisit" class="operateBtn">
                                                回访
                                            </div>
                                            <div @click="goAppointment(scope.row)" v-if="scope.row.customerType != 3 && toAppointment" class="operateBtn">
                                                转预约
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                            
                            <el-row class="pagination-cont">
                                <el-pagination
                                    @size-change="handleSizeChange"
                                    background
                                    @current-change="handleCurrentChange"
                                    :current-page="item.pageControl.pageNum"
                                    :page-sizes="pageSizeList"
                                    :page-size="item.pageControl.pageSize"
                                    :total="item.pageControl.total"
									:pager-count="5"
                                    layout="total, sizes, prev, pager, next, jumper"
                                />
                            </el-row>
                        </el-row>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>
<script>
import pathTracking from '@/components/common/pathTracking'             // 面包屑路径
import advancedSearch from'@/components/common/filter/advancedSearch'   // 搜索列表
import tablecom from './../components/pages/table'
import { getList, getCreateBy, getResource } from './axios.js'
import datas from './datas.js'
// 获取按钮权限配置的方法
import operationConfig from '@/utils/btnsPermission'
export default {
    name: 'customerList',
    data() {
        return {
            path: ['CRM', '客户管理', '客户列表'],
            activeName: 'allSearchBox',                      // 默认选中的tab
            tabNavs: _.cloneDeep(datas.tabNavs),             // tabs
            pageSizeList: [10, 20, 30, 40],
            founderList: [],                                 // 预约人列表
            createBtns: false,
            exportIcon: false,
            seeDetail: false,
            editBtn: false,
            returnVisit: false,
            toAppointment: false
        }
    },
    components: {
        tablecom,
        pathTracking,
        advancedSearch
    },
    methods: {
        // 创建
        createBtn(){
			this.$router.push({name:'createCustomer'})
        },
        //查看
		goDetail(par){
			var customerID = par.id;
			var isBuy = par.isBuy;
			this.$router.push({path:'checkDetail',query:{id:customerID,isBuy:isBuy ? '是' : '否'}});
        },
        //编辑
        goEdit(par){
            var customerID = par.id;
            var isBuy = par.isBuy;
            this.$router.push({path:'edit',query:{id:customerID,isBuy:isBuy ? '是' : '否'}})
        },
        //回访
        goReturnVisit(par){
            var customerID = par.id;
            var isBuy = par.isBuy;
            this.$router.push({name:'returnVisit',query:{id:customerID,isBuy:isBuy ? '是' : '否'}})
        },
        //转预约
        goAppointment(par){
			var customerType = par.customerType;
			this.phone = par.phone;
			this.getPhone(this.phone,par.id);
        },
        //根据手机号查询是否有预约单
		getPhone(phone,id){
            var that = this;
            that.$ajax({
                method:'GET',
                url: api.crm + '/reservationInfo/getReservationByUserId?userId='+ id,
            }).then((res) => {
				var data = res.data;
				if(data.status == 200){
					if(data.result.infoType == 1){//有未完结的预约单
                        that.$message({
                            message: '您已有一个未完结的预约单',
                            type: 'warning'
                        });
                            setTimeout(function(){
                            that.$router.replace({name:'customerList'})
                        },2000)
                    }else{
						//console.log('没有未完结订单,于是就获取填充的信息');
						that.$router.push({name:'toAppointment',query:{id:id}})
                    }
                }else if(data.status == 500 && data.code == 1000050){
					that.$message({
                        message: data.msg,
                        type: 'warning'
                    });
                    //that.$router.replace({name:'customerList'})
				}else{
					that.$message({
                        message: data.msg,
                        type: 'warning'
                    });
				}
			})
        },
        // 查询按钮
        goSearch(name, index , tip) {
            this.tabNavs[index].pageControl.pageNum = 1
            this.toSearch(name, index , tip)
        },
        // 查询的方法
        toSearch(name, index , tip) {
            let val = this.$refs[name][0].getFormData();
            let regExp = /^[ ]*$/, obj = {};
            val.map(ele => {
                if(ele.value !== '' && ele.value != undefined && !regExp.test(ele.value)) {
                    if(ele.key === 'createDate') {
                        obj.createDateStart = new Date(ele.value[0]).getTime()
                        obj.createDateEnd = new Date(ele.value[1]).getTime() + 24 * 60 * 60 * 1000 - 1000
                    }else {
                        obj[ele.key] = ele.value
                    }
                }
            })
            if(!Object.keys(obj).length) {
                if(tip !== 'withoutTip') {
                    this.$message({
                        message: '请输入查询内容进行查询',
                        type: 'warning'
                    })
                }
                return
            }else {
                index && (obj.customerType = index)
            }
            
            // 请求列表数据
            let { pageSize, pageNum, total } = this.tabNavs[index].pageControl
            getList(obj, pageSize, pageNum).then(res => {
                if(res.data.status === 200) {
                    this.tabNavs[index].pageControl.total = res.data.result.total
                    this.tabNavs[index].tableContent = res.data.result.result
                }else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
            }).catch(err => {
                this.$message({
                    message: '查询失败',
                    type: 'warning'
                })
            })
        },
        // 获取创建人
        getFounder() {
            getCreateBy().then(res => {
                if(res.data.status === 200) {
                    let arr = [
                        {
                            label: '请选择创建人',
                            value: undefined
                        }
                    ]
                    res.data.result.map(ele => {
                        arr.push({
                            label: ele.userName,
                            value: ele.sapUserId
                        })
                    })
                    this.founderList = arr
                    this.tabNavs.map(ele => {
                        ele.options.items.map(item => {
                            item.key === 'createBy' && (item.data = arr)
                        })
                    })
                }
            }).catch(err => {
                console.error('get founder list filed', err)
            })
        },
        // 改变列表每页条数
        handleSizeChange(size) {
            this.tabNavs.map((ele, index) => {
                if(ele.name === this.activeName) {
                    ele.pageControl.pageSize = size
                    this.toSearch(this.activeName, index)
                }
            })
        },
        // 页码变化
        handleCurrentChange(pageNum) {
            this.tabNavs.map((ele, index) => {
                if(ele.name === this.activeName) {
                    ele.pageControl.pageNum = pageNum
                    this.toSearch(this.activeName, index)
                }
            })
        },
        translateData(data, item) {
            let res = ''
            switch (item.prop) {
                case 'customerType':
                    data[item.prop] == 1 && (res = '成交客户')
                    data[item.prop] == 2 && (res = '潜在客户')
                    data[item.prop] == 3 && (res = '预约中客户')
                    break;
                case 'isRegister':
                    data[item.prop] == 1 ? (res = '是') : (res = '否')
                    break;
                case 'isReservation':
                    data[item.prop] == 1 ? (res = '是') : (res = '否')
                    break;
                case 'isBuy':
                    data[item.prop] == 1 ? (res = '是') : (res = '否')
                    break;
                case 'isCallback':
                    data[item.prop] == 1 ? (res = '是') : (res = '否')
                    break;
                default: 
                    res = data[item.prop]
                    break;
            }
            return res
        },
        // 获取预约来源
        async getResourceInfo() {
            let res = await getResource();
            getResource().then(res => {
                if(res.status === 200) {
                    let arr = [{
                        label: '请选择客户来源',
                        value: undefined
                    }]
                    res.data.result.map(ele => {
                        let obj = {}
                        obj.value = ele.value
                        obj.label = ele.value
                        arr.push(obj)
                    })
                    this.tabNavs.forEach(item => {
                        item.options.items.forEach(ele => {
                            if(ele.key === 'source') {
                                ele.data = arr
                            }
                        });
                    })
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 按钮权限
        btnsControl() {
            let permission = operationConfig(this.$route);
            this.createBtns = false
            this.exportIcon = false
            this.seeDetail = false
            this.editBtn = false
            this.returnVisit = false
            this.toAppointment = false
            permission.forEach(ele => {
                if(ele.menu_name === '创建客户') {
                    this.createBtns = true
                }else if(ele.menu_name === '导出') {
                    this.exportIcon = true
                }else if(ele.menu_name === '查看') {
                    this.seeDetail = true
                }else if(ele.menu_name === '编辑') {
                    this.editBtn = true
                }else if(ele.menu_name === '回访') {
                    this.returnVisit = true
                }else if(ele.menu_name === '转预约') {
                    this.toAppointment = true
                }
            })
        }
    },
    mounted() {
        this.getFounder();
        this.getResourceInfo();
        this.btnsControl();
    },
    activated() {
        this.btnsControl();
        this.tabNavs.map((ele, index) => {
            if(ele.name === this.activeName) {
                this.toSearch(this.activeName, index, 'withoutTip')
            }
        })
    },
    watch: {
        tabNavs: {
    　　　　 handler(newValue, oldValue) {},
    　　　　 deep: true,
            immediate: true
    　　}
    }
}
</script>
<style scoped>
    .table-title {
        width: 100%;
        height: 58px;
        background-color: #fff;
        border-radius: 8px 8px 0px 0px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        /* overflow: hidden; */
    }

    .table-title .table-icon {
        width: 6px;
        height: 18px;
        background-color: #7e6b5a;
        float: left;
        margin-left: 19px;
    }

    .table-title .table-fl {
        font-size: 16px;
        color: #222222;
        margin-left: 8px;
    }
    .pageContent{
        padding: 16px;
    }
    .navContent{
        background: #F3F3F3;
        margin-top: 0 !important
    }
    .tableLayout{
        margin-top:10px;
    }
    .createBtn{
        height: 40px;
        width: 100px;
        display: flex;
		align-items: center;
		justify-content: center;
        background: #7E6B5A;
        color: #FFF;
        text-align: center;
        border-radius: 20px;
        font-size: 14px;
        cursor: pointer;
    }
    .operate-btn {
        width: 72px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 16px;
        border: solid 1px #7e6b5a;
        font-size: 14px;
        color: #7e6b5a;
        cursor: pointer;
        margin-right: 1rem;
    }
    .btnsCan{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .operateBtn{
        width: 5rem;
        margin: 0 4px;
        height: 2.4rem;
        cursor: pointer;
        line-height: 2.4rem;
        border-radius: 1.2rem;
        color: #7E6B5A;
        border: 1px solid #7E6B5A;
    }
    .pagination-cont{
        height: 8.8rem;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;
    }
    .exportIcon{
        margin-top: 0;
        margin-right: 2px;
        width: 14px;
        height:14px;
    }
	.iconPlus{
		width: 12px;
		height: 12px;
		margin-right: 4px
	}
	.iconLayout{
		width: 12px;
		height: 12px;
		margin-right: 4px
	}
</style>
